import {Buffer} from "buffer";
import {SID} from "./SID";
import {MAC} from "./MAC";
import {AxdrType} from "../asn1.axdr/AxdrType";
import {ReverseByteArrayInputStream} from "../ReverseByteArrayInputStream";
import {ReverseByteArrayOutputStream} from "../ReverseByteArrayOutputStream";


export class SID_MAC implements AxdrType{

    dataCode : Buffer | null = null;
    sid : SID | null = null;
    mac : MAC | null = null;

    constructor() {

    }

    set_dataCode(dataCode : Buffer){
        this.dataCode = dataCode;
    }

    set_all(sid : SID, mac : MAC){
        this.sid = sid;
        this.mac = mac;
    }

    setSID(sid : SID){
        this.sid = sid;
    }

    setMAC(mac : MAC){
        this.mac = mac;
    }

    decode(input: ReverseByteArrayInputStream): number {
        let codeLength = 0;

        this.sid = new SID();
        codeLength += this.sid.decode(input);

        this.mac = new MAC();
        codeLength += this.mac.decode(input);

        return codeLength;

    }

    encode(output: ReverseByteArrayOutputStream): number {
        let codeLength;

        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (let i = this.dataCode.length - 1; i >= 0; i--) {
                output.write(this.dataCode[i]);
            }
        } else {
            if(this.sid != null && this.mac != null){
                codeLength = 0;
                codeLength += this.mac.encode(output);
                codeLength += this.sid.encode(output);
            }else{
                throw new Error("sid || mac is null");
            }
        }
        return codeLength;
    }

    encodeAndSave(encodingSizeGuess: number) {
        let revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    toString(): string {
        if (this.sid != null && this.mac != null) {
            "sequence: {"+ "sid: " + this.sid + ", mac: " + this.mac  + "}";
        } else {
            return "sid || mac is null";
        }
    }

}
